package com.xinke.edu.mypetadoption.Activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.xinke.edu.mypetadoption.databinding.CreateAccountActitvtyBinding;
import com.xinke.edu.mypetadoption.entity.ResultBody;
import com.xinke.edu.mypetadoption.entity.User;
import com.xinke.edu.mypetadoption.net.RetrofitUtil;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class CreateAccountActivity extends AppCompatActivity {
    CreateAccountActitvtyBinding binding;
    // 用户类型选项
    private String[] userTypes = {"普通用户", "商家", "管理员"};

    int role = 3; // 角色：1-管理员，2-商家，3-普通用户

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = CreateAccountActitvtyBinding.inflate(LayoutInflater.from(this));
        setContentView(binding.getRoot());

        // 初始化权限下拉框
        initPermissionSpinner();

        // 注册按钮点击事件
        binding.createRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                register();
            }
        });

        // 立即登录按钮点击事件
        binding.createLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 初始化权限下拉框
     */
    private void initPermissionSpinner() {
        // 创建适配器，将数据与Spinner关联
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,  // 下拉项样式
                userTypes
        );
        // 设置下拉列表的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 给Spinner设置适配器
        binding.permissionSpinner.setAdapter(adapter);

        // 设置默认选中第一项（普通用户）
        binding.permissionSpinner.setSelection(0);

        // 监听选择事件
        binding.permissionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 获取选中的用户类型
                // String selectedType = userTypes[position];
                // 在这里可以根据选择的类型执行不同的逻辑
                if (position == 0) {
                    // 普通用户逻辑
                    role = 3;
                } else if (position == 1) {
                    // 商家逻辑
                    role = 2;
                } else if (position == 2) {
                    // 管理员逻辑
                    role = 1;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 未选择时的处理（一般不会触发）
            }
        });
    }

    /**
     * 用户注册方法
     */
    public void register() {
        String account = binding.createPhone.getText().toString();
        String password = binding.createPassword.getText().toString();
        String confirmPassword = binding.createPassword2.getText().toString();

        // 参数验证
        if (TextUtils.isEmpty(account)) {
            Toast.makeText(this, "账号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!password.equals(confirmPassword)) {
            Toast.makeText(this, "两次密码必须相同", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建User对象
        User user = new User();
        user.setUsername(account);
        user.setPassword(password);
        user.setRole((byte) role);

        System.out.printf("666");

        // 发送注册请求
        RetrofitUtil.getApi().register(user)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResultBody>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResultBody resultBody) {
                        if (resultBody.getCode() == 200) {
                            Toast.makeText(CreateAccountActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(CreateAccountActivity.this, resultBody.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Toast.makeText(CreateAccountActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放Binding资源（避免内存泄漏）
        binding = null;
    }
}